package com.example.a13001.shoppingmalltemplate.activitys;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.example.a13001.shoppingmalltemplate.R;
import com.example.a13001.shoppingmalltemplate.adapters.GridImageAdapter;
import com.example.a13001.shoppingmalltemplate.base.AppConstants;
import com.example.a13001.shoppingmalltemplate.base.BaseActivity;
import com.example.a13001.shoppingmalltemplate.modle.AddressOrderId;
import com.example.a13001.shoppingmalltemplate.modle.AfterSale;
import com.example.a13001.shoppingmalltemplate.modle.CommonResult;
import com.example.a13001.shoppingmalltemplate.modle.ShouHouDetail;
import com.example.a13001.shoppingmalltemplate.modle.UpFile;
import com.example.a13001.shoppingmalltemplate.mvpview.ApplyAfterSaleView;
import com.example.a13001.shoppingmalltemplate.presenter.ApplyAfterSalePredenter;
import com.example.a13001.shoppingmalltemplate.utils.FullyGridLayoutManager;
import com.example.a13001.shoppingmalltemplate.utils.GlideUtils;
import com.example.a13001.shoppingmalltemplate.utils.MyUtils;
import com.example.a13001.shoppingmalltemplate.utils.Utils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.RxPermissions;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.smarttop.library.bean.City;
import com.smarttop.library.bean.County;
import com.smarttop.library.bean.Province;
import com.smarttop.library.bean.Street;
import com.smarttop.library.db.manager.AddressDictManager;
import com.smarttop.library.widget.AddressSelector;
import com.smarttop.library.widget.BottomDialog;
import com.smarttop.library.widget.OnAddressSelectedListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class ApplyAfterSaleActivity extends BaseActivity implements OnAddressSelectedListener, AddressSelector.OnDialogCloseListener {

    @BindView(R.id.iv_title_back)
    ImageView ivTitleBack;
    @BindView(R.id.tv_title_center)
    TextView tvTitleCenter;
    @BindView(R.id.recycler_aftersale)
    RecyclerView recyclerAftersale;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.rl_root)
    RelativeLayout rlRoot;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.tv_diqu)
    TextView tvDiqu;
    @BindView(R.id.ll_address)
    LinearLayout llAddress;
    @BindView(R.id.et_addressdetail)
    EditText etAddressdetail;
    @BindView(R.id.et_postalcode)
    EditText etPostalcode;
    @BindView(R.id.iv_applyaftersale_goodsimage)
    ImageView ivApplyaftersaleGoodsimage;
    @BindView(R.id.tv_applyaftersale_goodsname)
    TextView tvApplyaftersaleGoodsname;
    @BindView(R.id.tv_applyaftersale_goodsprice)
    TextView tvApplyaftersaleGoodsprice;
    @BindView(R.id.tv_applyaftersale_goodsdescribe)
    TextView tvApplyaftersaleGoodsdescribe;
    @BindView(R.id.tv_applyaftersale_goodsnum)
    TextView tvApplyaftersaleGoodsnum;
    @BindView(R.id.tv_applyaftersale_commit)
    TextView tvApplyaftersaleCommit;
    @BindView(R.id.tv_applyaftersale_orderid)
    TextView tvApplyaftersaleOrderid;
    @BindView(R.id.iv_applyaftersale_jian)
    ImageView ivApplyaftersaleJian;
    @BindView(R.id.iv_applyaftersale_num)
    TextView ivApplyaftersaleNum;
    @BindView(R.id.iv_applyaftersale_jia)
    ImageView ivApplyaftersaleJia;
    @BindView(R.id.rb_applyaftersale_fapiao)
    RadioButton rbApplyaftersaleFapiao;
    @BindView(R.id.rb_applyaftersale_jiancebaogao)
    RadioButton rbApplyaftersaleJiancebaogao;
    @BindView(R.id.rb_applyaftersale_qitawenjian)
    RadioButton rbApplyaftersaleQitawenjian;
    @BindView(R.id.rg_applyaftersale_pingjv)
    RadioGroup rgApplyaftersalePingjv;
    @BindView(R.id.et_applyaftersale_question)
    EditText etApplyaftersaleQuestion;
    @BindView(R.id.rb_applyaftersale_tuihuo)
    RadioButton rbApplyaftersaleTuihuo;
    @BindView(R.id.rb_applyaftersale_huanhuo)
    RadioButton rbApplyaftersaleHuanhuo;
    @BindView(R.id.rb_applyaftersale_weixiu)
    RadioButton rbApplyaftersaleWeixiu;
    @BindView(R.id.rg_applyaftersale_tuihuo)
    RadioGroup rgApplyaftersaleTuihuo;
    private GridImageAdapter adapter;
    private List<LocalMedia> selectList = new ArrayList<>();
    private int mCartId;
    private int mCommodityId;
    private int mNumber;
    private double mPrice;
    private String mCartimg;
    private String mProperty;
    private String mGoodsName;
    private int orderid;
    //地址选择相关
    private PopupWindow popWnd;
    private BottomDialog dialog;
    private AddressDictManager addressDictManager;
    private String provinceCode;
    private String cityCode;
    private String countyCode;
    private String streetCode;
    private String mProvince;
    private String mProvince1;
    private String mCity;
    private String mCity1;
    private String mArea;
    private String mArea1;
    private int addressDefault = 0;
    private ApplyAfterSalePredenter applyAfterSalePredenter = new ApplyAfterSalePredenter(ApplyAfterSaleActivity.this);
    private static final String TAG = "ApplyAfterSaleActivity";
    private String code;
    private String timeStamp;
    private int repairstype;
    private int repairsnumber;
    private int repairsproof;
    private String repairscontent;
    private String repairsimages;
    private String repairsname;
    private String repairsphone;
    private String Receiptaddress;
    private String repairszipcode;
    private List<String> mListImage = new ArrayList<>();
    private StringBuffer buf;
    private String mOrdernumber;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply_after_sale);
        ButterKnife.bind(this);
        applyAfterSalePredenter.onCreate();
        applyAfterSalePredenter.attachView(applyAfterSaleView);
        String safetyCode = MyUtils.getMetaValue(ApplyAfterSaleActivity.this, "safetyCode");
        code = Utils.md5(safetyCode + Utils.getTimeStamp());
        timeStamp = Utils.getTimeStamp();
        initData();
        if (getIntent() != null) {
            mCartId = getIntent().getIntExtra("cartid", 0);
            mCommodityId = getIntent().getIntExtra("commodityId", 0);
            mNumber = getIntent().getIntExtra("number", 0);
            orderid = getIntent().getIntExtra("orderid", 0);
            mPrice = getIntent().getDoubleExtra("price", 0);
            mCartimg = getIntent().getStringExtra("cartimg");
            mProperty = getIntent().getStringExtra("property");
            mGoodsName = getIntent().getStringExtra("name");
            mOrdernumber = getIntent().getStringExtra("ordernumber");
        }
        GlideUtils.setNetImage(ApplyAfterSaleActivity.this, AppConstants.INTERNET_HEAD + mCartimg, ivApplyaftersaleGoodsimage);
        tvApplyaftersaleGoodsprice.setText("价格：¥" + mPrice);
        tvApplyaftersaleGoodsnum.setText("数量X" + mNumber);
        tvApplyaftersaleGoodsname.setText(mGoodsName);
        tvApplyaftersaleGoodsdescribe.setText(mProperty);
        tvApplyaftersaleOrderid.setText("订单号："+mOrdernumber);
        Log.e(TAG, "onCreate: " + AppConstants.COMPANY_ID + "==code==" + code + "==timeStamp==" + timeStamp + "==id==" + String.valueOf(orderid)+"==cartid=="+mCartId+"==shangp=="+mCommodityId);
        applyAfterSalePredenter.getAddressOrderId(AppConstants.COMPANY_ID, code, timeStamp, String.valueOf(orderid));
        initListener();
    }

    private void initListener() {
        rgApplyaftersaleTuihuo.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                //售后服务类型，1 退货 2 换货 3 维修
                switch (i){
                    case R.id.rb_applyaftersale_tuihuo:
                        repairstype=1;
                        break;
                    case R.id.rb_applyaftersale_huanhuo:
                        repairstype=2;
                        break;
                    case R.id.rb_applyaftersale_weixiu:
                        repairstype=3;
                        break;
                }
            }
        });

        rgApplyaftersalePingjv.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                //申请售后商品申请凭据，1 发票信息 2 检测报告 3 其它文件
                switch (i){
                    case R.id.rb_applyaftersale_fapiao:
                        repairsproof=1;
                        break;
                    case R.id.rb_applyaftersale_jiancebaogao:
                        repairsproof=2;
                        break;
                    case R.id.rb_applyaftersale_qitawenjian:
                        repairsproof=3;
                        break;
                }
            }
        });
    }

    ApplyAfterSaleView applyAfterSaleView = new ApplyAfterSaleView() {
        @Override
        public void onSuccess(CommonResult commonResult) {
            Log.e(TAG, "onSuccess: " + commonResult.toString());
            int status = commonResult.getStatus();
            if (status > 0) {
                finish();
            } else {

            }
        }

        @Override
        public void onSuccessGetAfterSaleList(AfterSale afterSale) {

        }

        @Override
        public void onSuccessGetAddressOrderId(AddressOrderId addressOrderId) {
            Log.e(TAG, "onSuccessGetAddressOrderId: " + addressOrderId.toString());
            int status = addressOrderId.getStatus();
            if (status > 0) {
                etName.setText(addressOrderId.getReceiptName() != null ? addressOrderId.getReceiptName() : "");
                etPhone.setText(addressOrderId.getReceiptPhone() != null ? addressOrderId.getReceiptPhone() : "");
                tvDiqu.setText(addressOrderId.getAddressProvince() + addressOrderId.getAddressCity() + addressOrderId.getAddressArea());
                etAddressdetail.setText(addressOrderId.getAddressXX() != null ? addressOrderId.getAddressXX() : "");
                etPostalcode.setText(addressOrderId.getReciptZipCode());
            } else {

            }
        }

        @Override
        public void onSuccessGetShouHouDetail(ShouHouDetail shouHouDetail) {

        }

        //上传文件
        @Override
        public void onSuccessUpFile(UpFile upFile) {
            Log.e(TAG, "onSuccessUpFile: "+upFile.toString() );
            int status=upFile.getStatus();
            if (status>0){
                mListImage.add(upFile.getData());
                Log.e(TAG, "onCompleted: " + mListImage.toString());
                if (mListImage.size() == selectList.size()) {
                    Log.e(TAG, "onViewClicked: " + mListImage.toString());
                    for (int i = 0; i < mListImage.size(); i++) {
                        buf.append(mListImage.get(i)).append("|");
                    }
                    if (buf.length() > 0) {
                        //方法一  : substring
                        System.out.println(buf.substring(0, buf.length() - 1));
//                            //方法二 ：replace
//                            System.out.println(buf.replace(buf.length() - 1, buf.length(), ""));
//                            //方法三： deleteCharAt
//                            System.out.println(buf.deleteCharAt(buf.length()-1));
                    }
                    Log.e(TAG, "onActivityResult: 图片--buf---》" + buf.toString());
//                Log.e(TAG, "onViewClicked: code==" + code + "==timeStamp==" + timeStamp + "==mCartId=="
//                        + mCartId + "==mCommodityId==" + mCommodityId + "==content==" + content + "==level=="
//                        + level + "==lable==" + lable + "==listImage.toString()==" + buf.toString());
                    applyAfterSalePredenter.commitShouHou(AppConstants.COMPANY_ID, code, timeStamp, mCartId,mCommodityId,
                            String.valueOf(orderid), repairstype, repairsnumber, String.valueOf(repairsproof), repairscontent,
                            buf.toString(), repairsname, repairsphone, Receiptaddress, repairszipcode);
                }
            }else{

            }
        }

        @Override
        public void onError(String result) {
            Log.e(TAG, "onError: " + result);
        }
    };

    /**
     * 初始化数据源
     */
    private void initData() {
        tvTitleCenter.setText("商品售后");
        FullyGridLayoutManager manager = new FullyGridLayoutManager(ApplyAfterSaleActivity.this, 4, GridLayoutManager.VERTICAL, false);
        recyclerAftersale.setLayoutManager(manager);
        adapter = new GridImageAdapter(ApplyAfterSaleActivity.this, onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(9);
        recyclerAftersale.setAdapter(adapter);
        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                if (selectList.size() > 0) {
                    LocalMedia media = selectList.get(position);
                    String pictureType = media.getPictureType();
                    int mediaType = PictureMimeType.pictureToVideo(pictureType);
                    switch (mediaType) {
                        case 1:
                            // 预览图片 可自定长按保存路径
                            //PictureSelector.create(ApplyAfterSaleActivity.this).themeStyle(themeId).externalPicturePreview(position, "/custom_file", selectList);
                            PictureSelector.create(ApplyAfterSaleActivity.this).themeStyle(R.style.picture_default_style).openExternalPreview(position, selectList);
                            break;
                        case 2:
                            // 预览视频
                            PictureSelector.create(ApplyAfterSaleActivity.this).externalPictureVideo(media.getPath());
                            break;

                    }
                }
            }
        });

        // 清空图片缓存，包括裁剪、压缩后的图片 注意:必须要在上传完成后调用 必须要获取权限
        RxPermissions permissions = new RxPermissions(this);
        permissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(Boolean aBoolean) {
                if (aBoolean) {
                    PictureFileUtils.deleteCacheDirFile(ApplyAfterSaleActivity.this);
                } else {
                    Toast.makeText(ApplyAfterSaleActivity.this,
                            getString(R.string.picture_jurisdiction), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        });
    }

    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {

            // 进入相册 以下是例子：不需要的api可以不写
            PictureSelector.create(ApplyAfterSaleActivity.this)
                    .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture_white_style,R.style.picture_QQ_style,R.style.picture_Sina_style
                    .maxSelectNum(9)// 最大图片选择数量
                    .minSelectNum(1)// 最小选择数量
                    .imageSpanCount(4)// 每行显示个数
                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                    .previewImage(true)// 是否可预览图片
                    .previewVideo(true)// 是否可预览视频
                    .enablePreviewAudio(true) // 是否可播放音频
                    .isCamera(true)// 是否显示拍照按钮
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    //.imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                    //.setOutputCameraPath("/CustomPath")// 自定义拍照保存路径
                    .enableCrop(false)// 是否裁剪
                    .compress(true)// 是否压缩
                    .synOrAsy(true)//同步true或异步false 压缩 默认同步
//                        .compressSavePath(getPath())//压缩图片保存地址
//                        .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                    .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
//                        .withAspectRatio(aspect_ratio_x, aspect_ratio_y)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                    .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                    .isGif(false)// 是否显示gif图片
                    .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                    .circleDimmedLayer(false)// 是否圆形裁剪
                    .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                    .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                    .openClickSound(false)// 是否开启点击声音
                    .selectionMedia(selectList)// 是否传入已选图片
                    //.isDragFrame(false)// 是否可拖动裁剪框(固定)
//                        .videoMaxSecond(15)
//                        .videoMinSecond(10)
                    //.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                    //.cropCompressQuality(90)// 裁剪压缩质量 默认100
                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                    //.cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
                    //.rotateEnabled(true) // 裁剪是否可旋转图片
                    //.scaleEnabled(true)// 裁剪是否可放大缩小图片
                    //.videoQuality()// 视频录制质量 0 or 1
                    //.videoSecond()//显示多少秒以内的视频or音频也可适用
                    //.recordVideoSecond()//录制视频秒数 默认60s
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code

        }

    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                    for (LocalMedia media : selectList) {
                        Log.i("图片-----》", media.getPath());
                    }
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    /**
     * 各控件的点击事件
     *
     * @param view
     */
    @OnClick({R.id.iv_title_back, R.id.ll_address, R.id.tv_applyaftersale_commit,R.id.iv_applyaftersale_jia,R.id.iv_applyaftersale_jian})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_title_back:
                onBackPressed();
                break;
            //地址
            case R.id.ll_address:
                if (dialog != null) {
                    dialog.show();
                } else {
                    dialog = new BottomDialog(this);
                    dialog.setOnAddressSelectedListener(this);
                    dialog.setDialogDismisListener(this);
                    dialog.setTextSize(14);//设置字体的大小

                    dialog.setIndicatorBackgroundColor(R.color.ff2828);//设置指示器的颜色
                    dialog.setTextSelectedColor(R.color.ff2828);//设置字体获得焦点的颜色
                    dialog.setTextUnSelectedColor(R.color.t333);//设置字体没有获得焦点的颜色
                    dialog.show();
                }


                break;
            case R.id.tv_applyaftersale_commit:
                repairsnumber= Integer.parseInt(ivApplyaftersaleNum.getText().toString().trim());
                repairscontent=etApplyaftersaleQuestion.getText().toString().trim();
                repairsname=etName.getText().toString().trim();
                repairsphone=etPhone.getText().toString().trim();
                String diqv=tvDiqu.getText().toString().trim();
                String detailaddress=etAddressdetail.getText().toString().trim();
                Receiptaddress=diqv.concat(detailaddress);
                repairszipcode= etPostalcode.getText().toString().trim();
                buf = new StringBuffer();
                for (LocalMedia media : selectList) {
                    File file = new File(media.getPath());
                    RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"), file);
                    MultipartBody.Part part = MultipartBody.Part.createFormData("filePath", file.getName(), requestBody);
                    applyAfterSalePredenter.upFile(AppConstants.COMPANY_ID, code, timeStamp, part);

                }

                break;
                //数量加
            case R.id.iv_applyaftersale_jia:
                int currentCount= Integer.parseInt(ivApplyaftersaleNum.getText().toString().trim());
                if (currentCount == mNumber) {
                    return;
                }
                currentCount++;
                ivApplyaftersaleNum.setText(currentCount+"");

                break;
                //数量减
            case R.id.iv_applyaftersale_jian:
                int currentCount1= Integer.parseInt(ivApplyaftersaleNum.getText().toString().trim());
                if (currentCount1 == 1) {
                    return;
                }
                currentCount1--;
                ivApplyaftersaleNum.setText(currentCount1+"");

                break;

        }
    }

    private String getPath() {
        String path = Environment.getExternalStorageDirectory() + "/Luban/image/";
        File file = new File(path);
        if (file.mkdirs()) {
            return path;
        }
        return path;
    }

    @Override
    public void dialogclose() {
        if (dialog != null) {
            dialog.dismiss();
        }
    }

    @Override
    public void onAddressSelected(Province province, City city, County county, Street street) {
        provinceCode = (province == null ? "" : province.code);
        cityCode = (city == null ? "" : city.code);
        countyCode = (county == null ? "" : county.code);
        streetCode = (street == null ? "" : street.code);
        String s = (province == null ? "" : province.name) + (city == null ? "" : city.name) + (county == null ? "" : county.name) +
                (street == null ? "" : street.name);
        mProvince = province == null ? "" : province.name;
        mProvince1 = mProvince + "|" + provinceCode;
        mCity = city == null ? "" : city.name;
        mCity1 = mCity + "|" + cityCode;
        mArea = county == null ? "" : county.name;
        mArea1 = mArea + "|" + countyCode;
        tvDiqu.setText(s);
        if (dialog != null) {
            dialog.dismiss();
        }
    }
}
